#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdlib.h>

int cmp(const void* p1, const void* p2)
{
    return (*(int*)p1 - *(int*)p2);
}

int* intersection(int* nums1, int nums1Size, int* nums2, int nums2Size, int* returnSize) {
    qsort(nums1, nums1Size, sizeof(int), cmp);
    qsort(nums2, nums2Size, sizeof(int), cmp);
    int i = 0;
    int begain1 = 0;
    int begain2 = 0;
    int* NewArray = (int*)malloc(sizeof(int) * nums1Size);
    if (NewArray == NULL)
    {
        perror("malloc fail");
        return -1;
    }

    while (begain1 < nums1Size && begain2 < nums2Size)
    {
        if (nums1[begain1] < nums2[begain2])
        {
            begain1++;
        }
        else if (nums1[begain1] > nums2[begain2])
        {
            begain2++;
        }
        else
        {
            if (i == 0 || nums1[begain1] != NewArray[i - 1])
            {
                NewArray[i] = nums1[begain1];
                i++;
                begain1++;
                begain2++;
            }
        }
    }
    *returnSize = i;

    return NewArray;
}

int main()
{
    int arr[] = { 2,2 };
    int numarr[] = { 1,2,2,1 };
    int sz1 = sizeof(arr) / sizeof(arr[0]);
    int sz2 = sizeof(numarr) / sizeof(numarr[0]);
    int size = 0;
    int* ret = intersection(arr, sz1, numarr, sz2, &size);
    for (int i = 0; i < size; i++)
    {
        printf("%d ", ret[i]);
    }
    printf("\n");
    free(ret);
    ret = NULL;


	return 0;
}